package org.aurora.ten;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author : qiaodan
 * @date : 2024/8/21 15:39
 * @description CountDownLatch原理剖析
 */
public class CountDownLatchAnalysis {
    private static volatile CountDownLatch countDownLatch = new CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {
        //实际项目中避免手动创建线程
//        Thread one = new Thread(new Runnable(){
//            @Override
//            public void run(){
//                try {
//                    Thread.sleep(1000);
//                    countDownLatch.countDown();
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        });
//        Thread two = new Thread(new Runnable(){
//            @Override
//            public void run(){
//                try {
//                    Thread.sleep(1000);
//                    countDownLatch.countDown();
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        });

        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        threadPool.submit(new Runnable(){
            @Override
            public void run(){
                try {
                    Thread.sleep(1000);
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        threadPool.submit(new Runnable(){
            @Override
            public void run(){
                try {
                    Thread.sleep(1000);
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        long startTime = System.nanoTime();
        System.out.println("等待子线程执行");
        countDownLatch.await();
        long endTime = System.nanoTime();
        System.out.println("执行时间："+(endTime - startTime) + " ns");
        threadPool.shutdown();
    }
}
